package com.jsyxdl.k3cloud.listener;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hustcad.plm.pdm.flowbusiness.model.entity.FlowObject;
import com.hustcad.plm.pdm.partbom.dto.ChildPartsFiltersDTO;
import com.hustcad.plm.pdm.partbom.dto.PartBomTree;
import com.hustcad.plm.pdm.partbom.dto.PartUsageLink;
import com.hustcad.plm.pdm.partbom.service.TyplmPartAlternateService;
import com.hustcad.plm.pdm.partbom.service.TyplmPartBomService;
import com.hustcad.plm.pdm.partbom.vo.PartBomTreeByFilterVO;
import com.hustcad.plm.pdm.partbom.vo.PartDetailsVO;
import com.hustcad.plm.pdm.user.service.ErpBomService;
import com.hustcad.plm.pdm.user.service.impl.ErpHistoricalVersion;
import com.jsyxdl.entity.PartUsageLinkDiffResultDTO;
import com.jsyxdl.k3cloud.listener.handling.*;
import com.jsyxdl.k3cloud.service.ErpWorkedTaskService;
import com.jsyxdl.k3cloud.service.WorkedTaskService;
import com.jsyxdl.k3cloud.utils.HttpMethodEnum;
import com.jsyxdl.k3cloud.utils.PlmPartOptionUtils;
import com.jsyxdl.k3cloud.utils.SendErpDataUtils;
import com.jsyxdl.service.ErpK3cloudService;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import javax.sql.DataSource;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.*;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class K3CloudHttpService {

    private ErpHistoricalVersion erpHistoricalVersion;

    private WorkFlowObjectPackageRoutine workFlowObjectPackageRoutine;

    public SendErpDataUtils sendErpDataUtils;


    private boolean autoCookie;
    private String kdserviceSessionid;
    private String cookieStr;

    public String plmEntityOid;


    public K3CloudHttpService(DataSource dataSource, boolean autoCookie) {
        this.autoCookie = autoCookie;
        if(erpHistoricalVersion==null){
            erpHistoricalVersion=new ErpHistoricalVersion();
        }
        if(workFlowObjectPackageRoutine==null){
            workFlowObjectPackageRoutine=new WorkFlowObjectPackageRoutine();
        }
        if(sendErpDataUtils==null){
            sendErpDataUtils=new SendErpDataUtils();
        }
    }

    public WorkFlowObjectPackageRoutine getWorkFlowObjectPackageRoutine() {
        return workFlowObjectPackageRoutine;
    }

    public boolean isAutoCookie() {
        return autoCookie;
    }
    public void setAutoCookie(boolean autoCookie) {
        this.autoCookie = autoCookie;
    }

    public String getCookieStr() {
        return cookieStr;
    }

    public void setCookieStr(String cookieStr) {
        this.cookieStr = cookieStr;
    }

    public String getKdserviceSessionid() {
        return kdserviceSessionid;
    }

    public void setKdserviceSessionid(String kdserviceSessionid) {
        this.kdserviceSessionid = kdserviceSessionid;
    }

    public ErpHistoricalVersion getErpHistoricalVersion() {
        return erpHistoricalVersion;
    }


    public static BigInteger generateUniqueId() {
        long timestamp = Instant.now().toEpochMilli();
        long sequence = System.nanoTime() % 1000000;

        String idStr = timestamp + "" + 1 + "" + sequence;
        return new BigInteger(idStr);
    }


    public List<Map<String, Object>> getOptions(String code, String k3cloud)throws Exception{
        ErpK3cloudService erpK3cloudService= SpringUtil.getBean(ErpK3cloudService.class);
        return erpK3cloudService.getOptions(code,k3cloud);
    }
    public Map<String, Object> getExecutionType(String code,String k3cloud){
        ErpK3cloudService erpK3cloudService= SpringUtil.getBean(ErpK3cloudService.class);
        List<Map<String, Object>> outSettingList=erpK3cloudService.getExecutionType(code,k3cloud);
        if(outSettingList==null || outSettingList.size()==0) return null;
        return outSettingList.get(0);
    }



    //递归获取BOM
    public void getRecursionBom(Set<PartBomTree> list, List<PartBomTree> bomList){
        for( PartBomTree partBomTree: list) {
            if(partBomTree.getChildren()!=null && partBomTree.getChildren().size()>0){
                bomList.add(partBomTree);
                getRecursionBom(partBomTree.getChildren(),bomList);
            }
        }
    }



    public Map<String,Object> plmToK3CloudOut(String code,String k3cloud,Map<String,Object> parameters, Map<String,Object> bomKeyValue)throws Exception{

        Map<String,Object> inMap=getInTreeMap(code,k3cloud);

        Map<String,Object> keyValue=new HashMap<>();
        if(parameters.size()>0){
            for(Map.Entry<String,Object> entity: parameters.entrySet()){
                Map<String,Object> part= (Map<String, Object>) entity.getValue();
                for(Map.Entry<String,Object> inEntity: inMap.entrySet()){
                    setInTree((List<Map<String, Object>>) inEntity.getValue(),part.get(inEntity.getKey()),keyValue);
                }
            }
        }

        keyValue.putAll(bomKeyValue);
        Map<String,Object> saveMateriel=new HashMap<>();
        getOutTree(code,k3cloud,saveMateriel,keyValue,0);
        return saveMateriel;
    }
    public Map<String,Object> getInTreeMap(String code,String k3cloud){

        ErpK3cloudService erpK3cloudService= SpringUtil.getBean(ErpK3cloudService.class);

        List<Map<String, Object>> inSettingList=erpK3cloudService.getInTreeMap(code,k3cloud);
        Map<String,Object> settingMap=new HashMap<>();
        for(int i=0;i<inSettingList.size();i++){
            String plm_source_type_id= (String) inSettingList.get(i).get("plm_source_type_id");
            if(settingMap.containsKey(plm_source_type_id)){
                List<Map<String, Object>> settingList= (List<Map<String, Object>>) settingMap.get(plm_source_type_id);
                settingList.add(inSettingList.get(i));
                settingMap.put(plm_source_type_id,settingList);
            }
            else{
                List<Map<String, Object>> settingList=new ArrayList<>();
                settingList.add(inSettingList.get(i));
                settingMap.put(plm_source_type_id,settingList);
            }
        }
        return settingMap;

    }
    public void setInTree(List<Map<String, Object>> settingList,Object parameter,Map<String,Object> keyValue) throws Exception{

        Map<String,Object> inTree=new HashMap<>();
        setParameterToTree(settingList,"0",inTree);
        Map<String,Object> inTreeData=new HashMap<>();
        JSONObject obj=null;
        if(parameter instanceof String){
            obj=JSONObject.parseObject((String) parameter);
        }
        else if(parameter instanceof JSONObject){
            obj= (JSONObject) parameter;
        }
        else if(parameter instanceof Map){
            obj= JSONObject.parseObject(JSONObject.toJSONString(parameter));
        }
        else{
            obj= JSONObject.parseObject(JSONObject.toJSONString(parameter));
        }


        getInTreeData(inTree,inTreeData,obj,keyValue);

    }
    private static void getInTreeData(Map<String,Object> tree,Object mapOrList,Object jsonParameter,Map<String,Object> keyValue){
        Set<Map.Entry<String,Object>> set=tree.entrySet();
        for(Map.Entry<String,Object> entity: set) {
            if(entity.getValue() instanceof Map){
                Map<String,Object> entityMap= (Map<String, Object>) entity.getValue();
                int valuation_type= -2;
                if(entityMap.get("valuation_type")!=null){
                    valuation_type= (int) entityMap.get("valuation_type");
                }
                int data_type=-2;
                if(entityMap.get("data_type")!=null){
                    data_type= (int) entityMap.get("data_type");
                }
                String node_key= (String) entityMap.get("node_key");
                String default_value= (String) entityMap.get("default_value");
                String node= (String) entityMap.get("node");

                if(valuation_type==0){
                    if(data_type==-2){
                        if(mapOrList instanceof Map){
                            List entityList=new ArrayList();
                            ((Map<String,Object>)mapOrList).put(entity.getKey(),entityList);
                            keyValue.put(node_key,entityList);

                            Map<String,Object> childMap=new HashMap<>();
                            entityList.add(childMap);
                            if(jsonParameter instanceof JSONObject){
                                getInTreeData(entityMap,childMap,((JSONObject)jsonParameter).get(entity.getKey()),keyValue);
                            }
                            else if(jsonParameter instanceof JSONArray){
                                getInTreeData(entityMap,childMap,jsonParameter,keyValue);
                            }

                        }
                    }
                    else if(data_type==-1){
                        if(mapOrList instanceof Map){
                            List entityList=new ArrayList();
                            ((Map<String,Object>)mapOrList).put(entity.getKey(),entityList);
                            keyValue.put(node_key,entityList);

                            Map<String,Object> childMap=new HashMap<>();
                            entityList.add(childMap);
                            if(jsonParameter instanceof JSONObject){
                                getInTreeData(entityMap,childMap,((JSONObject)jsonParameter).get(entity.getKey()),keyValue);
                            }
                            else if(jsonParameter instanceof JSONArray){
                                getInTreeData(entityMap,childMap,jsonParameter,keyValue);
                            }

                        }
                    }
                    else if(data_type==0){
                        Map<String,Object> childMap=new HashMap<>();
                        ((Map<String,Object>)mapOrList).put(entity.getKey(),childMap);
                        keyValue.put(node_key,childMap);
                        if(jsonParameter instanceof JSONObject){
                            getInTreeData(entityMap,childMap,((JSONObject)jsonParameter).get(entity.getKey()),keyValue);
                        }
                        else if(jsonParameter instanceof JSONArray){
                        }
                    }
                }
                else if(valuation_type== 1){

                    if(mapOrList instanceof Map){
                        if(data_type==5){
                            if(default_value==null){
                                ((Map<String,Object>)mapOrList).put(entity.getKey(),null);
                            }
                            else{
                                JSONObject v=JSONObject.parseObject(default_value);
                                keyValue.put(node_key,v.get("value"));
                                ((Map<String,Object>)mapOrList).put(entity.getKey(),v.get("value"));
                            }
                        }
                        else if(data_type==4){
                            if(default_value==null){
                                ((Map<String,Object>)mapOrList).put(entity.getKey(),null);
                            }
                            else{
                                JSONObject v=JSONObject.parseObject(default_value);
                                keyValue.put(node_key,v.getDoubleValue("value"));
                                ((Map<String,Object>)mapOrList).put(entity.getKey(),v.getDoubleValue("value"));
                            }
                        }
                        else{
                            if(default_value==null){
                                ((Map<String,Object>)mapOrList).put(entity.getKey(),null);
                            }
                            else{
                                JSONObject v=JSONObject.parseObject(default_value);
                                keyValue.put(node_key,v.get("value"));
                                ((Map<String,Object>)mapOrList).put(entity.getKey(),v.get("value"));
                            }
                        }
                    }
                    else if(mapOrList instanceof List){

                    }
                }
                else if(valuation_type==2){
                    if(mapOrList instanceof Map){
                        if(data_type==5){
                            if(jsonParameter==null){
                                ((Map<String,Object>)mapOrList).put(entity.getKey(),null);
                            }
                            else{
                                if(jsonParameter instanceof JSONObject){
                                    keyValue.put(node_key,((JSONObject)jsonParameter).get(entity.getKey()));
                                    ((Map<String,Object>)mapOrList).put(entity.getKey(),((JSONObject)jsonParameter).get(entity.getKey()));
                                }
                                else if(jsonParameter instanceof JSONArray){
                                    keyValue.put(node_key,((JSONArray)jsonParameter).getJSONObject(0).get(entity.getKey()));
                                    ((Map<String,Object>)mapOrList).put(entity.getKey(),((JSONArray)jsonParameter).getJSONObject(0).get(entity.getKey()));
                                }
                            }
                        }
                        else if(data_type==4){
                            if(jsonParameter==null){
                                ((Map<String,Object>)mapOrList).put(entity.getKey(),null);
                            }
                            else{
                                if(jsonParameter instanceof JSONObject){
                                    keyValue.put(node_key,((JSONObject)jsonParameter).getDoubleValue(entity.getKey()));
                                    ((Map<String,Object>)mapOrList).put(entity.getKey(),((JSONObject)jsonParameter).getDoubleValue(entity.getKey()));
                                }
                                else if(jsonParameter instanceof JSONArray){
                                    if(((JSONArray)jsonParameter).size()>0) {
                                        keyValue.put(node_key,((JSONArray)jsonParameter).getJSONObject(0).getDoubleValue(entity.getKey()));
                                        ((Map<String,Object>)mapOrList).put(entity.getKey(),((JSONArray)jsonParameter).getJSONObject(0).getDoubleValue(entity.getKey()));
                                    }
                                }
                            }
                        }
                        else if(data_type==-1){
                            List entityList=new ArrayList();
                            ((Map<String,Object>)mapOrList).put(entity.getKey(),entityList);
                            keyValue.put(node_key,entityList);

                            if(jsonParameter instanceof JSONObject){
                                JSONArray arr= (JSONArray) ((JSONObject)jsonParameter).get(entity.getKey());
                                if(arr!=null){
                                    for(int i=0;i<arr.size();i++){
                                        Map<String,Object> childMap=new HashMap<>();
                                        entityList.add(childMap);
                                        getInTreeData(entityMap,childMap,arr.get(i),childMap);
                                    }
                                }
                            }
                            else if(jsonParameter instanceof JSONArray){

                            }
                        }
                        else{
                            if(jsonParameter==null){
                                ((Map<String,Object>)mapOrList).put(entity.getKey(),null);
                            }
                            else{
                                if(jsonParameter instanceof JSONObject){
                                    keyValue.put(node_key,((JSONObject)jsonParameter).get(entity.getKey()));
                                    ((Map<String,Object>)mapOrList).put(entity.getKey(),((JSONObject)jsonParameter).get(entity.getKey()));
                                }
                                else if(jsonParameter instanceof JSONArray){

                                    if(((JSONArray)jsonParameter).size()>0){
                                        keyValue.put(node_key,((JSONArray)jsonParameter).getJSONObject(0).get(entity.getKey()));
                                        ((Map<String,Object>)mapOrList).put(entity.getKey(),((JSONArray)jsonParameter).getJSONObject(0).get(entity.getKey()));
                                    }

                                }
                            }
                        }
                    }
                    else if(mapOrList instanceof List){

                    }
                }
                else if(valuation_type==3){
                    if(mapOrList instanceof Map){
                        if(data_type==5){
                            if(jsonParameter==null){
                                ((Map<String,Object>)mapOrList).put(entity.getKey(),null);
                            }
                            else{
                                if(jsonParameter instanceof JSONObject){
                                    keyValue.put(node_key,((JSONObject)jsonParameter).get(entity.getKey()));
                                    ((Map<String,Object>)mapOrList).put(entity.getKey(),((JSONObject)jsonParameter).get(entity.getKey()));
                                }
                                else if(jsonParameter instanceof JSONArray){
                                    keyValue.put(node_key,((JSONArray)jsonParameter).getJSONObject(0).get(entity.getKey()));
                                    ((Map<String,Object>)mapOrList).put(entity.getKey(),((JSONArray)jsonParameter).getJSONObject(0).get(entity.getKey()));
                                }
                            }
                        }
                        else if(data_type==4){
                            if(jsonParameter==null){
                                ((Map<String,Object>)mapOrList).put(entity.getKey(),null);
                            }
                            else{
                                if(jsonParameter instanceof JSONObject){
                                    keyValue.put(node_key,((JSONObject)jsonParameter).getDoubleValue(entity.getKey()));
                                    ((Map<String,Object>)mapOrList).put(entity.getKey(),((JSONObject)jsonParameter).getDoubleValue(entity.getKey()));
                                }
                                else if(jsonParameter instanceof JSONArray){
                                    if(((JSONArray)jsonParameter).size()>0) {
                                        keyValue.put(node_key,((JSONArray)jsonParameter).getJSONObject(0).getDoubleValue(entity.getKey()));
                                        ((Map<String,Object>)mapOrList).put(entity.getKey(),((JSONArray)jsonParameter).getJSONObject(0).getDoubleValue(entity.getKey()));
                                    }
                                }
                            }
                        }
                        else if(data_type==-1){
                            List entityList=new ArrayList();
                            ((Map<String,Object>)mapOrList).put(entity.getKey(),entityList);
                            keyValue.put(node_key,entityList);

                            if(jsonParameter instanceof JSONObject){
                                JSONArray arr= (JSONArray) ((JSONObject)jsonParameter).get(entity.getKey());
                                if(arr!=null){
                                    for(int i=0;i<arr.size();i++){
                                        Map<String,Object> childMap=new HashMap<>();
                                        entityList.add(childMap);
                                        getInTreeData(entityMap,childMap,arr.get(i),childMap);
                                    }
                                }
                            }
                            else if(jsonParameter instanceof JSONArray){

                            }
                        }
                        else{
                            if(jsonParameter==null){
                                ((Map<String,Object>)mapOrList).put(entity.getKey(),null);
                            }
                            else{
                                if(jsonParameter instanceof JSONObject){
                                    keyValue.put(node,((JSONObject)jsonParameter).get(entity.getKey()));
                                    ((Map<String,Object>)mapOrList).put(entity.getKey(),((JSONObject)jsonParameter).get(entity.getKey()));
                                }
                                else if(jsonParameter instanceof JSONArray){

                                    if(((JSONArray)jsonParameter).size()>0){
                                        keyValue.put(node,((JSONArray)jsonParameter).getJSONObject(0).get(entity.getKey()));
                                        ((Map<String,Object>)mapOrList).put(entity.getKey(),((JSONArray)jsonParameter).getJSONObject(0).get(entity.getKey()));
                                    }

                                }
                            }
                        }
                    }
                    else if(mapOrList instanceof List){

                    }
                }

            }
        }
    }
    public void getOutTree(String code,String k3cloud,Map<String,Object> saveMateriel,Map<String,Object> keyValue,int k3cloudSave){
        ErpK3cloudService erpK3cloudService= SpringUtil.getBean(ErpK3cloudService.class);

        List<Map<String, Object>> outSettingList=erpK3cloudService.getOutTreeMap(code,k3cloud);
        Map<String,Object> outTree=new HashMap<>();
        setParameterToTree(outSettingList,"0",outTree);
        getOutTreeDataEx(outTree,saveMateriel,keyValue,false);
    }
    private static void getOutTreeDataEx(Map<String,Object> tree,Object saveMateriel,Map<String,Object> keyValue,boolean nodeValue){
        Set<Map.Entry<String,Object>> set=tree.entrySet();
        for(Map.Entry<String,Object> entity: set) {
            if(entity.getValue() instanceof Map){
                Map<String,Object> entityMap= (Map<String, Object>) entity.getValue();
                int valuation_type= -2;
                if(entityMap.get("valuation_type")!=null){
                    valuation_type= (int) entityMap.get("valuation_type");
                }
                int data_type=-2;
                if(entityMap.get("data_type")!=null){
                    data_type= (int) entityMap.get("data_type");
                }
                String default_value= (String) entityMap.get("default_value");
                int processing_strategy = 0;
                if(entityMap.get("processing_strategy")!=null){
                    processing_strategy =(int)entityMap.get("processing_strategy");

                }

                if(valuation_type==0){
                    if(data_type==-2){
                        if(saveMateriel instanceof Map){
                            List entityList=new ArrayList();
                            ((Map<String,Object>)saveMateriel).put(entity.getKey(),entityList);

                            for(Map.Entry<String,Object> bl:entityMap.entrySet()){
                                if(bl.getValue() instanceof Map){
                                    Map<String,Object> childMap=new HashMap<>();
                                    entityList.add(childMap);
                                    getOutTreeDataEx((Map<String,Object>)bl.getValue(),childMap,keyValue,nodeValue);
                                }
                            }
                        }
                    }
                    else if(data_type==-1){
                        if(saveMateriel instanceof Map){
                            List entityList=new ArrayList();
                            ((Map<String,Object>)saveMateriel).put(entity.getKey(),entityList);
                            Map<String,Object> childMap=new HashMap<>();
                            entityList.add(childMap);
                            getOutTreeDataEx(entityMap,childMap,keyValue,nodeValue);
                        }
                    }
                    else if(data_type==0){
                        Map<String,Object> childMap=new HashMap<>();
                        ((Map<String,Object>)saveMateriel).put(entity.getKey(),childMap);
                        getOutTreeDataEx(entityMap,childMap,keyValue,false);

                    }
                    else if(data_type==5){
                        if(saveMateriel instanceof Map){
                            ((Map<String,Object>)saveMateriel).put(entity.getKey(),new ArrayList<>());
                        }
                    }
                }
                else if(valuation_type== 1){
                    if(saveMateriel instanceof Map){
                        if(processing_strategy==1){
                            ((Map<String,Object>)saveMateriel).put(entity.getKey(),null);
                            continue;
                        }
                        if(data_type==5){
                            if(default_value==null){
                                ((Map<String,Object>)saveMateriel).put(entity.getKey(),null);
                            }
                            else{
                                JSONObject v=JSONObject.parseObject(default_value);
                                ((Map<String,Object>)saveMateriel).put(entity.getKey(),v.get("value"));
                            }
                        }
                        else if(data_type==4){
                            if(default_value==null){
                                ((Map<String,Object>)saveMateriel).put(entity.getKey(),null);
                            }
                            else{
                                JSONObject v=JSONObject.parseObject(default_value);
                                ((Map<String,Object>)saveMateriel).put(entity.getKey(),v.getDoubleValue("value"));
                            }
                        }
                        else if(data_type==2){
                            if(default_value==null){
                                ((Map<String,Object>)saveMateriel).put(entity.getKey(),null);
                            }
                            else{
                                JSONObject v=JSONObject.parseObject(default_value);
                                ((Map<String,Object>)saveMateriel).put(entity.getKey(),v.getBooleanValue("value"));
                            }
                        }
                        else if(data_type==8){
                            if(default_value==null){
                                ((Map<String,Object>)saveMateriel).put(entity.getKey(),null);
                            }
                            else{
                                JSONObject v=JSONObject.parseObject(default_value);
                                String timeStr=v.getString("value");
                                if("yyyy-MM-dd HH:mm:ss".equals(timeStr)){
                                    Timestamp updatestamp=new Timestamp(new Date().getTime());

                                    Instant instant = updatestamp.toInstant();
                                    LocalDateTime updatestampDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
                                    // 创建一个DateTimeFormatter对象，指定格式
                                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                                    timeStr=updatestampDateTime.format(formatter);
                                }
                                else if("yyyy-MM-dd".equals(timeStr)){
                                    Timestamp updatestamp=new Timestamp(new Date().getTime());

                                    Instant instant = updatestamp.toInstant();
                                    LocalDateTime updatestampDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
                                    // 创建一个DateTimeFormatter对象，指定格式
                                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                                    timeStr=updatestampDateTime.format(formatter);
                                }
                                ((Map<String,Object>)saveMateriel).put(entity.getKey(),timeStr);
                            }
                        }
                        else{
                            if(default_value==null){
                                ((Map<String,Object>)saveMateriel).put(entity.getKey(),null);
                            }
                            else{
                                JSONObject v=JSONObject.parseObject(default_value);
                                ((Map<String,Object>)saveMateriel).put(entity.getKey(),v.get("value"));
                            }
                        }
                    }
                    else if(saveMateriel instanceof List){
                    }
                }
                else if(valuation_type==2){
                    String in_key= (String) entityMap.get("in_key");
                    if(saveMateriel instanceof Map){
                        if(processing_strategy==1){
                            ((Map<String,Object>)saveMateriel).put(entity.getKey(),null);
                            continue;
                        }
                        if(data_type==5){
                            if(keyValue==null){
                                ((Map<String,Object>)saveMateriel).put(entity.getKey(),new ArrayList<>());
                            }
                            else{
                                if(keyValue.containsKey("huaz_options")){
                                    List<Map<String, Object>> options=(List<Map<String, Object>>)keyValue.get("huaz_options");
                                    String plm_source_type_id=null;
                                    for(Map<String,Object> option: options){
                                        if("BOM属性".equals(option.get("plmtype"))){
                                            plm_source_type_id= (String) option.get("plm_source_type_id");
                                            break;
                                        }
                                        else if("采购BOM属性".equals(option.get("plmtype"))){
                                            plm_source_type_id= (String) option.get("plm_source_type_id");
                                            break;
                                        }
                                    }
                                    if(plm_source_type_id!=null){
                                        List<Map<String, Object>> numberList= (List<Map<String, Object>>) keyValue.get(plm_source_type_id);
                                        List<String> numbers=new ArrayList<>();
                                        for(int a=0;a<numberList.size();a++){
                                            numbers.add((String) numberList.get(a).get(in_key));
                                        }
                                        ((Map<String,Object>)saveMateriel).put(entity.getKey(),numbers);
                                    }
                                }
                                else{
                                    Object inObj=keyValue.get(in_key);
                                    if(inObj instanceof String){
                                        List<String> inList=new ArrayList<>();
                                        inList.add((String) inObj);
                                        ((Map<String,Object>)saveMateriel).put(entity.getKey(),inList);
                                    }
                                    else{
                                        ((Map<String,Object>)saveMateriel).put(entity.getKey(),keyValue.get(in_key));
                                    }
                                }

                            }
                        }
                        else if(data_type==4){
                            if(keyValue==null){
                                ((Map<String,Object>)saveMateriel).put(entity.getKey(),null);
                            }
                            else{
                                Object inObj=keyValue.get(in_key);
                                if(inObj instanceof String){
                                    ((Map<String,Object>)saveMateriel).put(entity.getKey(),keyValue.get(in_key));
                                }
                                else{
                                    ((Map<String,Object>)saveMateriel).put(entity.getKey(),keyValue.get(in_key));
                                }
                            }
                        }
                        else if(data_type==2){
                            if(keyValue==null){
                                ((Map<String,Object>)saveMateriel).put(entity.getKey(),null);
                            }
                            else{
                                Object inObj=keyValue.get(in_key);
                                if(inObj instanceof JSONArray){
                                    JSONArray arr= (JSONArray) inObj;
                                    if(arr==null){
                                        ((Map<String,Object>)saveMateriel).put(entity.getKey(),null);
                                    }
                                    else{
                                        if(arr.size()>0){
                                            String booleanStr=arr.getString(0);
                                            if("".equals(booleanStr)==false){
                                                ((Map<String,Object>)saveMateriel).put(entity.getKey(),arr.getBooleanValue(0));
                                            }
                                            else{
                                                ((Map<String,Object>)saveMateriel).put(entity.getKey(),false);
                                            }
                                        }
                                        else{
                                            ((Map<String,Object>)saveMateriel).put(entity.getKey(),null);
                                        }
                                    }
                                }
                                else{
                                    ((Map<String,Object>)saveMateriel).put(entity.getKey(),keyValue.get(in_key));
                                }
                            }
                        }
                        else if(data_type==-1){
                            List entityList=new ArrayList();
                            ((Map<String,Object>)saveMateriel).put(entity.getKey(),entityList);
                            Object objList=keyValue.get(in_key);
                            if(objList instanceof ArrayList){
                                List<Map<String,Object>> arr= (List<Map<String,Object>>) keyValue.get(in_key);
                                for(int i=0;i<arr.size();i++){
                                    Map<String,Object> childMap=new HashMap<>();
                                    entityList.add(childMap);
                                    getOutTreeDataEx(entityMap,childMap,arr.get(i),nodeValue);
                                }
                            }
                            else if(objList instanceof JSONArray){
                                JSONArray arr= (JSONArray) keyValue.get(in_key);
                                for(int i=0;i<arr.size();i++){
                                    Map<String,Object> childMap=new HashMap<>();
                                    entityList.add(childMap);
                                    getOutTreeDataEx(entityMap,childMap,arr.getJSONObject(i),nodeValue);
                                }
                            }
                        }
                        else{
                            if(nodeValue==false){
                                if(keyValue==null){
                                    ((Map<String,Object>)saveMateriel).put(entity.getKey(),null);
                                }
                                else{
                                    Object objValue=keyValue.get(in_key);
                                    if(objValue==null){
                                        ((Map<String,Object>)saveMateriel).put(entity.getKey(),null);
                                    }
                                    else{
                                        if(objValue instanceof JSONArray){
                                            JSONArray objArr = (JSONArray) objValue;
                                            ((Map<String,Object>)saveMateriel).put(entity.getKey(),objArr.get(0));
                                        }
                                        else{
                                            ((Map<String,Object>)saveMateriel).put(entity.getKey(),objValue);
                                        }
                                    }
                                }
                            }
                            else{
                                if(keyValue==null){
                                    ((Map<String,Object>)saveMateriel).put(entity.getKey(),null);
                                }
                                else{
                                    ((Map<String,Object>)saveMateriel).put(entity.getKey(),keyValue.get(entity.getKey()));
                                }
                            }
                        }
                    }

                }
                else if(valuation_type==3){
                    String in_key= (String) entityMap.get("in_key");
                    if(saveMateriel instanceof Map){
                        if(processing_strategy==1){
                            ((Map<String,Object>)saveMateriel).put(entity.getKey(),null);
                            continue;
                        }
                        JSONObject vJson=JSONObject.parseObject(default_value);
                        String template=vJson.getString("value");

                        Map<String,Object> vakue= (Map<String,Object>) keyValue.get(in_key);
                        if(vakue!=null){
                            String message=replaceVariables(template,vakue);

                            ((Map<String,Object>)saveMateriel).put(entity.getKey(),message);
                        }

                    }

                }

            }
        }
    }
    public static String replaceVariables(String template, Map<String, Object> variables) {
        Pattern pattern = Pattern.compile("\\$\\{(\\w+)\\}");
        Matcher matcher = pattern.matcher(template);
        StringBuffer buffer = new StringBuffer();

        while (matcher.find()) {
            String key = matcher.group(1);
            Object obj=variables.getOrDefault(key, matcher.group());
            if(obj instanceof String){
                String replacement = (String) obj;
                matcher.appendReplacement(buffer, replacement);
            }
            else if(obj instanceof Long){
                String replacement =Long.toString((Long) obj);
                matcher.appendReplacement(buffer, replacement);
            }
            else if(obj instanceof Double){
                String replacement =Double.toString((Double) obj);
                matcher.appendReplacement(buffer, replacement);
            }
            else if(obj instanceof Float){
                String replacement =Float.toString((Float) obj);
                matcher.appendReplacement(buffer, replacement);
            }
        }
        matcher.appendTail(buffer);

        return buffer.toString();
    }


    public  JSONObject postServiceHttpToJSONObject(HttpMethodEnum httpMethodEnum, String uri, Map<String,Object> parameter) throws Exception{
        String url=httpMethodEnum.value()+uri;

        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig=RequestConfig.custom().setConnectTimeout(300000).setSocketTimeout(300000).build();
        httpPost.setConfig(requestConfig);
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        CloseableHttpResponse response = null;

        try {

            httpPost.setHeader("Content-Type","application/json; charset=utf-8");
            //httpPost.setHeader("Connection","close");

            if(cookieStr!=null){
                httpPost.setHeader("Cookie",cookieStr);
                if(kdserviceSessionid!=null){
                    httpPost.setHeader("kdservice-sessionid",kdserviceSessionid);
                }
            }



            JSONObject obj=null;
            if(parameter!=null){
                obj= JSONObject.parseObject(JSONObject.toJSONString(parameter));
                String send=obj.toString();
                StringEntity byteArrayEntity=new StringEntity(changeCharset(send,"ISO-8859-1"));
                byteArrayEntity.setContentType("application/json; charset=utf-8");
                httpPost.setEntity(byteArrayEntity);

            }



            response = httpClient.execute(httpPost);
            int status = response.getStatusLine().getStatusCode();
            if (status == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {

                    Header[] headers=response.getAllHeaders();
                    StringBuilder hreader=new StringBuilder();
                    Map<String,String> hreadsMap=new HashMap<>();
                    for(int i=0;i<headers.length;i++){
                        hreader.append(headers[i].getName()+": "+headers[i].getValue()+"\n");
                        if(autoCookie && cookieStr==null){
                            if("Set-Cookie".equals(headers[i].getName())){
                                String setCookie=headers[i].getValue();
                                String sub[]=setCookie.split("; ");
                                for(int y=0;y<sub.length;y++){
                                    hreadsMap.put(sub[y],"");
                                    if(sub[y].indexOf("kdservice-sessionid")!= -1){
                                        String tx[]=sub[y].split("=");
                                        if(tx.length==2) this.kdserviceSessionid=tx[1];
                                    }
                                }
                            }
                        }
                    }

                    if(autoCookie && cookieStr==null) {
                        cookieStr="";
                        for(Map.Entry<String,String> item: hreadsMap.entrySet()){
                            cookieStr+=item.getKey()+"; ";
                        }
                    }
                    JSONObject result=null;
                    String resultStr=new String(EntityUtils.toString(entity));
                    try {
                        result=JSONObject.parseObject(resultStr);
                        result.put("hreaders",hreader.toString());
                    }
                    catch (Exception e){
                        result=new JSONObject();
                        result.put("IsSuccess",false);
                        result.put("messages",resultStr);
                    }

                    return result;
                }
            }
            else{
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String error=EntityUtils.toString(entity);
                    return JSONObject.parseObject(new String(error));
                }
            }
        }
        finally {
            if (response != null) {
                try {
                    response.close();
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    public  JSONObject erpServiceHttpToJSONObject(String url, JSONObject parameter,String token) throws Exception{
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig=RequestConfig.custom().setConnectTimeout(3000000).setSocketTimeout(3000000).build();
        httpPost.setConfig(requestConfig);
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        CloseableHttpResponse response = null;

        try {

            httpPost.setHeader("Content-Type","application/json; charset=utf-8");
            httpPost.setHeader("Connection","close");
            if(token!=null){
                httpPost.setHeader("authorization",token);
                httpPost.setHeader("Authorization",token);

            }

            JSONObject obj=null;
            if(parameter!=null){
                obj= parameter;
                String send=obj.toString();
                StringEntity byteArrayEntity=new StringEntity(changeCharset(send,"ISO-8859-1"));
                byteArrayEntity.setContentType("application/json; charset=utf-8");
                httpPost.setEntity(byteArrayEntity);
            }

            response = httpClient.execute(httpPost);
            int status = response.getStatusLine().getStatusCode();
            if (status == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {

                    JSONObject result=null;
                    String resultStr=EntityUtils.toString(entity);
                    try {
                        result=JSONObject.parseObject(resultStr);
                    }
                    catch (Exception e){
                        e.printStackTrace();
                    }

                    return result;
                }
            }
            else{
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return JSONObject.parseObject(EntityUtils.toString(entity));
                }
            }
        }
        finally {
            if (response != null) {
                try {
                    response.close();
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    public  JSONObject getServiceHttpToJSONObject(String url, String token) throws Exception{
        HttpGet httpGet = new HttpGet(url);
        RequestConfig requestConfig=RequestConfig.custom().setConnectTimeout(3000000).setSocketTimeout(3000000).build();
        httpGet.setConfig(requestConfig);
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        CloseableHttpResponse response = null;

        try {

            httpGet.setHeader("Content-Type","application/json; charset=utf-8");
            httpGet.setHeader("Connection","close");
            if(token!=null){
                httpGet.setHeader("authorization",token);
                httpGet.setHeader("Authorization",token);

            }

            JSONObject obj=null;


            response = httpClient.execute(httpGet);
            int status = response.getStatusLine().getStatusCode();
            if (status == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {

                    JSONObject result=null;
                    String resultStr=EntityUtils.toString(entity);
                    try {
                        result=JSONObject.parseObject(resultStr);
                    }
                    catch (Exception e){
                        e.printStackTrace();
                    }

                    return result;
                }
            }
            else{
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return JSONObject.parseObject(EntityUtils.toString(entity));
                }
            }
        }
        finally {
            if (response != null) {
                try {
                    response.close();
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    public static String changeCharset(String str, String newCharset) {
        try {
            if (str != null) {
                //用默认字符编码解码字符串。
                byte[] bs = str.getBytes();
                //用新的字符编码生成字符串
                return new String(bs, newCharset);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }

    private static void setParameterToTree(List<Map<String, Object>> list,String parentId,Map<String,Object> entity){
        for(int i=0;i<list.size();i++){
            Map<String, Object> map=list.get(i);
            if(parentId.equals(map.get("parent_id"))){
                entity.put((String) map.get("node"),map);
                setParameterToTree(list,(String) map.get("id"),map);
            }
        }
    }


    public List<Map<String,Object>> jsonObjectToList(String json,String analysis){
        JSONObject obj=JSONObject.parseObject(json);
        List<Map<String,Object>> list=new ArrayList<>();
        jsonObjectChlider(list,obj,null,null,analysis);
        return list;
    }
    public void jsonObjectChlider(List<Map<String,Object>> list,Object entity,String entityUuid,String entityKey,String analysis){
        if(entity instanceof JSONObject){
            JSONObject f=(JSONObject) entity;
            for(Map.Entry<String,Object> e: f.getInnerMap().entrySet()){
                if(e.getValue() instanceof JSONObject){
                    Map<String,Object> map=new HashMap<>();
                    String uuid=UUID.randomUUID().toString();
                    map.put("id",uuid);
                    map.put("node",e.getKey());
                    map.put("node_key",uuid.replaceAll("-",""));
                    if(entityUuid==null){
                        map.put("parent_id","0");
                    }
                    else{
                        map.put("parent_id",entityUuid);
                    }
                    map.put("data_type",0);
                    map.put("valuation_type",0);
                    list.add(map);

                    jsonObjectChlider(list,e.getValue(),uuid,e.getKey(),analysis);
                }
                else if(e.getValue() instanceof JSONArray){
                    jsonObjectChlider(list,e.getValue(),entityUuid,e.getKey(),analysis);
                }
                else{
                    Map<String,Object> map=new HashMap<>();
                    String uuid=UUID.randomUUID().toString();
                    map.put("id",uuid);
                    map.put("node",e.getKey());
                    map.put("node_key",uuid.replaceAll("-",""));
                    if(entityUuid==null){
                        map.put("parent_id","0");
                    }
                    else{
                        map.put("parent_id",entityUuid);
                    }
                    dataType(map,e.getValue().getClass().getName(),e.getValue());
                    list.add(map);
                }
            }
        }
        else if(entity instanceof JSONArray){
            JSONArray arr=(JSONArray) entity;

            if(arr.size()==0){
                Map<String,Object> map=new HashMap<>();
                String uuid=UUID.randomUUID().toString();
                map.put("id",uuid);
                map.put("node",entityKey);
                map.put("node_key",uuid.replaceAll("-",""));
                if(entityUuid==null){
                    map.put("parent_id","0");
                }
                else{
                    map.put("parent_id",entityUuid);
                }
                map.put("data_type",5);
                map.put("valuation_type",0);
                list.add(map);
            }
            else{
                if("1".equals(analysis)){
                    Map<String,Object> map=new HashMap<>();
                    String uuid=UUID.randomUUID().toString();
                    map.put("id",uuid);
                    map.put("node",entityKey);
                    map.put("node_key",uuid.replaceAll("-",""));
                    if(entityUuid==null){
                        map.put("parent_id","0");
                    }
                    else{
                        map.put("parent_id",entityUuid);
                    }
                    map.put("data_type",-2);
                    map.put("valuation_type",0);
                    list.add(map);
                    for(int i=0;i<arr.size();i++){
                        map=new HashMap<>();
                        String auuid=UUID.randomUUID().toString();
                        map.put("id",auuid);
                        map.put("node",i);
                        map.put("node_key",auuid.replaceAll("-",""));
                        if(entityUuid==null){
                            map.put("parent_id","0");
                        }
                        else{
                            map.put("parent_id",uuid);
                        }
                        map.put("data_type",0);
                        map.put("valuation_type",0);
                        list.add(map);
                        jsonObjectChlider(list,arr.get(i),auuid,uuid,analysis);
                    }
                }
                else{
                    if(arr.get(0) instanceof JSONObject){
                        Map<String,Object> map=new HashMap<>();
                        String uuid=UUID.randomUUID().toString();
                        map.put("id",uuid);
                        map.put("node",entityKey);
                        map.put("node_key",uuid.replaceAll("-",""));
                        if(entityUuid==null){
                            map.put("parent_id","0");
                        }
                        else{
                            map.put("parent_id",entityUuid);
                        }
                        map.put("data_type",-1);
                        map.put("valuation_type",0);
                        list.add(map);
                        jsonObjectChlider(list,arr.get(0),uuid,entityKey,analysis);
                    }
                    else if(arr.get(0) instanceof JSONArray){
                        //jsonObjectChlider(list,arr.get(i),entityUuid,entityKey);
                    }
                    else{
                        Map<String,Object> map=new HashMap<>();
                        String uuid=UUID.randomUUID().toString();
                        map.put("id",uuid);
                        map.put("node",entityKey);
                        map.put("node_key",uuid.replaceAll("-",""));
                        if(entityUuid==null){
                            map.put("parent_id","0");
                        }
                        else{
                            map.put("parent_id",entityUuid);
                        }
                        map.put("data_type",5);
                        map.put("valuation_type",1);
                        JSONObject defaultValue=new JSONObject();
                        defaultValue.put("value",arr);
                        map.put("default_value",defaultValue.toJSONString());
                        list.add(map);
                    }
                }
            }
        }
        else{
            Map<String,Object> map=new HashMap<>();
            String uuid=UUID.randomUUID().toString();
            map.put("id",uuid);
            map.put("node",entityKey);
            map.put("node_key",uuid.replaceAll("-",""));
            if(entityUuid==null){
                map.put("parent_id","0");
            }
            else{
                map.put("parent_id",entityUuid);
            }
            map.put("data_type",5);
            map.put("valuation_type",0);
            list.add(map);
        }
    }

    public void dataType(Map<String,Object> map,String dataType,Object value){
        if("java.lang.String".equals(dataType)){
            if("false".equals(value) || "true".equals(value)){
                map.put("data_type",2);
            }
            else{
                map.put("data_type",1);
            }
        }
        else if("java.lang.Integer".equals(dataType)){
            map.put("data_type",3);
        }
        else if("java.math.BigDecimal".equals(dataType)){
            map.put("data_type",4);
        }
        else if("java.lang.Boolean".equals(dataType)){
            map.put("data_type",2);
        }

        map.put("valuation_type",1);

        JSONObject defaultValue=new JSONObject();
        if("java.math.BigDecimal".equals(dataType)){
            defaultValue.put("value", ((BigDecimal)value).doubleValue());

        }
        else{
            defaultValue.put("value",value);
        }

        map.put("default_value",defaultValue.toJSONString());

    }

    public List<Map<String,Object>> inPlmPartToList(List<Map<String,Object>> partList){
        List<Map<String,Object>> list=new ArrayList<>();
        inPlmPartToChildren(partList,list);
        return list;
    }
    public void inPlmPartToChildren(List<Map<String,Object>> list,List<Map<String,Object>> save){
        for(int i=0;i<list.size();i++){
            if(list.get(i).get("children")!=null){
                save.add(list.get(i));
                inPlmPartToChildren((List<Map<String, Object>>) list.get(i).get("children"),save);
            }
            else{
                save.add(list.get(i));
            }
        }
    }
    public void settingPlmPartToChildren(List<Map<String,Object>> list,List<Map<String,Object>> save,String parentId){
        for(int i=0;i<list.size();i++){
            if(parentId.equals(list.get(i).get("parent_id"))){
                Map<String,Object> node=new HashMap<>();
                node.put("label",list.get(i).get("node"));
                node.put("value",list.get(i).get("node_key"));
                if(node.containsKey("children")==false){
                    List<Map<String,Object>> children=new ArrayList<>();
                    node.put("children",children);
                }
                save.add(node);
                settingPlmPartToChildren(list, (List<Map<String, Object>>) node.get("children"), (String) list.get(i).get("id"));
            }
        }
    }
    public void settingPlmPartChildrenToNull(List<Map<String,Object>> list){
        for(int i=0;i<list.size();i++){
            if(list.get(i).containsKey("children")){
                List<Map<String,Object>> children= (List<Map<String, Object>>) list.get(i).get("children");
                if(children.size()==0){
                    list.get(i).remove("children");
                }
                else{
                    settingPlmPartChildrenToNull((List<Map<String, Object>>) list.get(i).get("children"));
                }
            }
        }
    }

    public void saveLogs(String plm_code,String erp_code,String exceptionMessage,String result,String outParameter,String plm_setting_object,String plm_setting_code) throws Exception {
        ErpK3cloudService erpK3cloudService= SpringUtil.getBean(ErpK3cloudService.class);
        erpK3cloudService.saveLogs(plm_code,erp_code,UUID.randomUUID().toString(),outParameter,result,plm_setting_object,plm_setting_code,exceptionMessage);
    }

    /**
     * ERP返回结果处理
     * @param httpResult
     * @param executionType
     * @return
     */
    public JSONObject erpResultDispose(JSONObject httpResult,Map<String, Object> executionType,Map<String, Object> outMap) throws Exception {
        if(httpResult!=null){
            String uri= (String) executionType.get("uri");
            String formid= (String) executionType.get("formid");
            String code= (String) executionType.get("code");
            String k3cloud= (String) executionType.get("k3cloud");
            String plm_code= (String) executionType.get("plm_code");

            if("/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Delete.common.kdsvc".equals(uri)){
                httpResult = new JSONObject();
                JSONObject resultObj=new JSONObject();
                JSONObject responseStatus=new JSONObject();
                responseStatus.put("IsSuccess",true);
                responseStatus.put("msg","删除");
                resultObj.put("ResponseStatus",responseStatus);
                httpResult.put("Result",resultObj);
                saveLogs(plm_code,"","成功",httpResult.toJSONString(),JSONObject.toJSONString(outMap),k3cloud,code);
                return httpResult;
            }
            else if("/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.UnAudit.common.kdsvc".equals(uri)){
                httpResult = new JSONObject();
                JSONObject resultObj=new JSONObject();
                JSONObject responseStatus=new JSONObject();
                responseStatus.put("IsSuccess",true);
                responseStatus.put("msg","反审核");
                resultObj.put("ResponseStatus",responseStatus);
                httpResult.put("Result",resultObj);
                saveLogs(plm_code,"","成功",httpResult.toJSONString(),JSONObject.toJSONString(outMap),k3cloud,code);
                return httpResult;
            }
            else if("/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.GroupSave.common.kdsvc".equals(uri)){
                JSONObject erpResult=httpResult.getJSONObject("Result");
                if(erpResult!=null){
                    JSONObject responseStatus=erpResult.getJSONObject("ResponseStatus");
                    if(responseStatus.getBooleanValue("IsSuccess")==false){
                        if(responseStatus.containsKey("Errors")) {
                            String erp_process= "";
                            JSONArray SuccessEntitys=new JSONArray();

                            JSONArray Errors = responseStatus.getJSONArray("Errors");
                            for(int a=0;a<Errors.size();a++) {
                                JSONObject err = Errors.getJSONObject(a);
                                if (err.containsKey("Message")) {
                                    String Message=err.getString("Message");
                                    if(Message.endsWith("的编码重复\r\n")){
                                        Message=Message.substring(Message.indexOf("为"));
                                        erp_process = Message.replaceAll("[^a-zA-Z0-9_.]", "");
                                        JSONObject obj=new JSONObject();
                                        obj.put("Number",erp_process);
                                        SuccessEntitys.add(obj);
                                        responseStatus.put("SuccessEntitys",SuccessEntitys);
                                        responseStatus.put("IsSuccess",true);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else{
                JSONObject erpResult=httpResult.getJSONObject("Result");
                if(erpResult!=null){
                    JSONObject responseStatus=erpResult.getJSONObject("ResponseStatus");
                    if(responseStatus.getBooleanValue("IsSuccess")==false){
                        if(responseStatus.containsKey("Errors")){
                            JSONArray Errors=responseStatus.getJSONArray("Errors");
                            boolean isError=false;
                            String erp_process= "";
                            JSONArray SuccessEntitys=new JSONArray();
                            boolean update=false;
                            if("BD_MATERIAL".equals(formid)){
                                for(int a=0;a<Errors.size();a++){
                                    JSONObject err=Errors.getJSONObject(a);
                                    if(err.containsKey("Message")){
                                        String Message=err.getString("Message");
                                        if(Message.startsWith("系统中已存在相同编码")){
                                            erp_process = Message.replaceAll("[^a-zA-Z0-9_.]", "");
                                            JSONObject obj=new JSONObject();
                                            obj.put("Number",erp_process);
                                            SuccessEntitys.add(obj);
                                            update=true;
                                            Errors.remove(a);
                                            a--;
                                        }
                                        else if(Message.endsWith("已审核的单据不允许提交!")){
                                            erp_process = Message.replaceAll("[^a-zA-Z0-9_.]", "");
                                            JSONObject obj=new JSONObject();
                                            obj.put("Number",erp_process);
                                            SuccessEntitys.add(obj);
                                            Errors.remove(a);
                                            a--;
                                        }
                                        else if(Message.endsWith("数据已经审核, 无需再审!")){
                                            erp_process = Message.replaceAll("[^a-zA-Z0-9_.]", "");
                                            JSONObject obj=new JSONObject();
                                            obj.put("Number",erp_process);
                                            SuccessEntitys.add(obj);
                                            Errors.remove(a);
                                            a--;
                                        }
                                        else if(Message.endsWith("审核中的数据无需重复提交!")){
                                            erp_process = Message.replaceAll("[^a-zA-Z0-9_.]", "");
                                            JSONObject obj=new JSONObject();
                                            obj.put("Number",erp_process);
                                            SuccessEntitys.add(obj);
                                            Errors.remove(a);
                                            a--;
                                        }
                                        else{
                                            isError=true;
                                        }
                                    }
                                }
                            }
                            else if("ENG_Substitution".equals(formid)){
                                for(int a=0;a<Errors.size();a++){
                                    JSONObject err=Errors.getJSONObject(a);
                                    if(err.containsKey("Message")){
                                        String Message=err.getString("Message");
                                        if(Message.startsWith("系统中已存在相同编码")){
                                            erp_process = Message.replaceAll("[^a-zA-Z0-9_.]", "");
                                            JSONObject obj=new JSONObject();
                                            obj.put("Number",erp_process);
                                            SuccessEntitys.add(obj);
                                        }
                                        else{
                                            isError=true;
                                        }
                                    }
                                }
                            }
                            else if("ENG_BOM".equals(formid)){
                                for(int a=0;a<Errors.size();a++){
                                    JSONObject err=Errors.getJSONObject(a);
                                    if(err.containsKey("Message")){
                                        String Message=err.getString("Message");
                                        if(Message.startsWith("系统中已存在相同编码")){
                                            erp_process = Message.replaceAll("[^a-zA-Z0-9_.]", "");
                                            JSONObject obj=new JSONObject();
                                            obj.put("Number",erp_process);
                                            SuccessEntitys.add(obj);
                                            Errors.remove(a);
                                            a--;
                                        }
                                        else if(Message.endsWith("的BOM版本，请重新设置！")){
                                            String errStr=Message.substring(0,Message.indexOf("已经存在"));
                                            erp_process = errStr.replaceAll("[^a-zA-Z0-9_.]", "");
                                            JSONObject obj=new JSONObject();
                                            obj.put("Number",erp_process);
                                            SuccessEntitys.add(obj);
                                            Errors.remove(a);
                                            a--;
                                        }
                                        else if(Message.endsWith("的物料清单，数据已经禁用!")){
                                            String errStr=Message;
                                            erp_process = errStr.replaceAll("[^a-zA-Z0-9_.]", "");
                                            JSONObject obj=new JSONObject();
                                            obj.put("Number",erp_process);
                                            SuccessEntitys.add(obj);
                                            Errors.remove(a);
                                            a--;
                                        }
                                        else{
                                            isError=true;
                                        }
                                    }
                                }
                            }
                            else if("BAS_PreBaseDataTwo".equals(formid)){
                                for(int a=0;a<Errors.size();a++){
                                    JSONObject err=Errors.getJSONObject(a);
                                    if(err.containsKey("Message")){
                                        String Message=err.getString("Message");
                                        if(Message.startsWith("系统中已存在相同编码")){
                                            erp_process = Message.replaceAll("[^a-zA-Z0-9_.]", "");
                                            JSONObject obj=new JSONObject();
                                            obj.put("Number",erp_process);
                                            SuccessEntitys.add(obj);
                                        }
                                        else{
                                            isError=true;
                                        }
                                    }
                                }
                            }
                            else if("PUR_Requisition".equals(formid)){
                                for(int a=0;a<Errors.size();a++){
                                    JSONObject err=Errors.getJSONObject(a);
                                    if(err.containsKey("Message")){
                                        String Message=err.getString("Message");
                                        if(Message.startsWith("系统中已存在相同编码")){
                                            erp_process = Message.replaceAll("[^a-zA-Z0-9_.]", "");
                                            JSONObject obj=new JSONObject();
                                            obj.put("Number",erp_process);
                                            SuccessEntitys.add(obj);
                                        }
                                        else{
                                            isError=true;
                                        }
                                    }
                                }
                            }
                            else if("STK_OutStockApply".equals(formid)){
                                isError=true;
                            }

                            if(isError){
                                saveLogs(plm_code,erp_process,"失败",responseStatus.toJSONString(),JSONObject.toJSONString(outMap),k3cloud,code);
                                return httpResult;
                            }
                            else{
                                JSONObject resultObj=new JSONObject();
                                JSONObject plmStatus=new JSONObject();
                                plmStatus.put("IsSuccess",true);
                                plmStatus.put("msg",String.format("成功添加物料%s",erp_process));
                                plmStatus.put("SuccessEntitys",SuccessEntitys);
                                resultObj.put("ResponseStatus",plmStatus);
                                httpResult.put("Result",resultObj);
                                httpResult.put("update",update);
                                boolean saveLog=true;
                                if("/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save.common.kdsvc".equals(uri)){
                                    if("BD_MATERIAL".equals(formid)){
                                        saveLog=false;
                                    }
                                }
                                if("/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.BatchSave.common.kdsvc".equals(uri)){
                                    if("BD_MATERIAL".equals(formid)){
                                        saveLog=false;
                                    }
                                }
                                if("/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Submit.common.kdsvc".equals(uri)){
                                    if("BD_MATERIAL".equals(formid)){
                                        saveLog=false;
                                    }
                                }
                                if("/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Audit.common.kdsvc".equals(uri)){
                                    if("BD_MATERIAL".equals(formid)){
                                        saveLog=false;
                                    }
                                }
                                if(saveLog){
                                    saveLogs(plm_code,erp_process,"成功",responseStatus.toJSONString(),JSONObject.toJSONString(outMap),k3cloud,code);
                                }
                                return httpResult;
                            }
                        }
                    }
                    else{
                        JSONArray successEntitys = responseStatus.getJSONArray("SuccessEntitys");
                        String erpNumber="";
                        if (successEntitys.size() > 0) {
                            erpNumber = successEntitys.getJSONObject(0).getString("Number");
                        }
                        saveLogs(plm_code,erpNumber,"成功",responseStatus.toJSONString(),JSONObject.toJSONString(outMap),k3cloud,code);

                    }
                }
            }
        }
        return httpResult;

    }

    public JSONObject plmToK3CloudTaskWorkderByParameter(String code, String k3cloud, JSONObject parameter)
            throws Exception {
        return SendErpDataUtils.plmToK3CloudTaskWorkderByParameter(code, k3cloud, parameter);
    }

}
